package com.wu.project.admin.service.impl;

import cn.hutool.core.date.format.FastDateFormat;
import com.wu.project.admin.component.JsonResult;
import com.wu.project.admin.dao.GoodsDao;
import com.wu.project.admin.entity.*;
import com.wu.project.admin.service.GoodsService;
import com.wu.project.admin.util.CommonResultUtil;
import com.wu.project.admin.util.FileUtil;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author xuan
 */
@Service
public class GoodsServiceImpl implements GoodsService {

    private final FastDateFormat fastDateFormat = FastDateFormat.getInstance("yyyyMMddHHmmss");

    private final FastDateFormat simpleDataFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    Logger logger = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Autowired
    GoodsDao goodsDao;

    @Override
    public void downloadXlsDemo(HttpServletResponse response) throws IOException, WriteException {

        if (!new File(System.getProperty("user.dir") + "/demo.xls").exists()) {
            createXlsFile();
        }
        FileUtil.Instance.download(System.getProperty("user.dir") + "/demo.xls", "demo.xls", response);
    }

    private void createXlsFile() throws IOException, WriteException {
        //创建文件，设置文件名。文件默认保存在当前位置
        WritableWorkbook book = Workbook.createWorkbook(new File(System.getProperty("user.dir") + "/demo.xls"));
        //生成名为“first”的工作表，参数0表示这是第一页
        WritableSheet sheet = book.createSheet("第一页", 0);
        List<String> list = Arrays.asList("商品名称", "商品颜色", "工种", "厂家", "厂家地址", "品牌",
                "商品型号", "商品产地", "商品单位", "商品发货地", "商品说明", "商品服务");
        //在Label对象的构造子中指名单元格位置是第一列第一行(0,0) 以及单元格内容为test
        for (int i = 0; i < list.size(); i++) {
            Label label = new Label(i, 0, list.get(i));
            sheet.addCell(label);
        }
        //写进文件，关闭文件
        book.write();
        book.close();
    }

    @Override
    public void uploadXls(MultipartFile file) {
        String fileName = "upload@" + fastDateFormat.format(new Date()) + ".xls";
        String fullPath = System.getProperty("user.dir") + "/" + fileName;
        try {
            file.transferTo(new File(fullPath));
        } catch (IOException e) {
            logger.error("写出xls文件异常");
        }

        try {
            FileInputStream fis = new FileInputStream(fullPath);
            jxl.Workbook rwb = Workbook.getWorkbook(fis);
            Sheet sheet = rwb.getSheet(0);
            List<GoodsDTO> xlsDataList = new LinkedList<>();
            // 获得行数
            int rows = sheet.getRows();
            // 获得列数
            int cols = sheet.getColumns();
            // 读取数据
            for (int row = 1; row < rows; row++) {
                GoodsDTO goodsDTO = new GoodsDTO();
                for (int col = 0; col < cols; col++) {
                    Cell cell = sheet.getCell(col, row);
                    switch (col) {
                        case 0:
                            goodsDTO.setShopGoodsName(cell.getContents());
                            break;
                        case 1:
                            goodsDTO.setShopGoodsColor(cell.getContents());
                            break;
                        case 2:
                            goodsDTO.setShopGoodsProfession(cell.getContents());
                            break;
                        case 3:
                            goodsDTO.setShopGoodsManufacturers(cell.getContents());
                            break;
                        case 4:
                            goodsDTO.setShopGoodsManufacturerAdd(cell.getContents());
                            break;
                        case 5:
                            goodsDTO.setShopGoodsBrand(cell.getContents());
                            break;
                        case 6:
                            goodsDTO.setShopGoodsModel(cell.getContents());
                            break;
                        case 7:
                            goodsDTO.setShopGoodsTexture(cell.getContents());
                            break;
                        case 8:
                            goodsDTO.setShopGoodsAddress(cell.getContents());
                            break;
                        case 9:
                            goodsDTO.setShopGoodsUnit(cell.getContents());
                            break;
                        case 10:
                            goodsDTO.setShopGoodsOrigin(cell.getContents());
                            break;
                        case 11:
                            goodsDTO.setShopGoodsExplain(cell.getContents());
                            break;
                        case 12:
                            goodsDTO.setShopGoodsServer(cell.getContents());
                            break;
                        default:
                            break;
                    }
                }
                xlsDataList.add(goodsDTO);
            }

            if (xlsDataList.size() > 0) {
                goodsDao.insertGoodsList(xlsDataList);
            }
        } catch (IOException | BiffException e) {
            e.printStackTrace();
        }

    }

    @Override
    public JsonResult getGoods(GoodsQueryVO goodsQueryVO) {
        Integer offset = CommonResultUtil.Instance.getOffset(goodsQueryVO.getPageNum(), goodsQueryVO.getPageSize());
        goodsQueryVO.setOffset(offset);

        List<GoodsDTO> goodsList = goodsDao.queryGoodsList(goodsQueryVO);
        Integer count = goodsDao.queryGoodsCount(goodsQueryVO);
        PageData pageData = new PageData();
        pageData.setPageSize(goodsQueryVO.getPageSize());
        pageData.setPageNum(goodsQueryVO.getPageNum());
        pageData.setTotal(count);
        pageData.setData(goodsList);

        return CommonResultUtil.Instance.success(pageData);
    }

    @Override
    public JsonResult goodsDown(GoodsQueryVO goodsQueryVO) {
        Integer count = goodsDao.downGoods(goodsQueryVO);
        if (count > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult updateGoods(GoodsDTO goodsDTO) {
        Integer count = goodsDao.updateGoods(goodsDTO);
        Integer integer = goodsDao.queryGoodsThree(goodsDTO);
        if (integer > 0){
            goodsDao.updateGoodsThree(goodsDTO);
        }else{
            goodsDao.insertGoodsThree(goodsDTO);
        }
        if (count > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult queryType1() {
        return CommonResultUtil.Instance.success(goodsDao.queryTypeOne());
    }

    @Override
    public JsonResult addTypeOne(String oneType) {
        String createTime = simpleDataFormat.format(new Date());
        Integer integer = goodsDao.addOneType(oneType, createTime, "1");
        if (integer > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult updateTypeOne(GoodsTypeOne goodsTypeOne) {
        Integer integer = goodsDao.updateOneType(goodsTypeOne);
        if (integer > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult deleteTypeOne(GoodsTypeOne goodsTypeOne) {
        Integer integer = goodsDao.deleteOneType(goodsTypeOne);
        if (integer > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult queryType2(Integer oneId) {
        List<GoodsTypeTwo> goodsTypeTwos = goodsDao.queryTypeTwo(oneId);
        return CommonResultUtil.Instance.success(goodsTypeTwos);
    }

    @Override
    public JsonResult addTypeTwo(String twoType, Long oneId) {
        String createTime = simpleDataFormat.format(new Date());
        Long twoMaxid = goodsDao.getTwoMaxid();
        Long newId = twoMaxid + 1L;
        Integer integer = goodsDao.addTwoType(newId, twoType, createTime, "1");
        Integer oneTwo = goodsDao.addOneTwo(oneId, newId, createTime, "1");
        if (integer > 0 && oneTwo > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult updateTypeTwo(GoodsTypeTwo goodsTypeTwo) {
        Integer integer = goodsDao.updateTwoType(goodsTypeTwo);
        if (integer > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult deleteTypeTwo(GoodsTypeTwo goodsTypeTwo) {
        Integer count = goodsDao.deleteTwoType(goodsTypeTwo);
        return count > 0 ? CommonResultUtil.Instance.success() : CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult getTwoAllData() {
        return CommonResultUtil.Instance.success(goodsDao.queryTwoAll());
    }

    @Override
    public JsonResult getThreeGoodsList(Integer twoId) {
        return CommonResultUtil.Instance.success(goodsDao.queryThreeList(twoId));
    }

    @Override
    public JsonResult addTypeThree(String threeType, Long twoId) {
        String createTime = simpleDataFormat.format(new Date());
        Long threeMaxid = goodsDao.getThreeMaxId();
        Long newId = threeMaxid + 1L;
        Integer integer = goodsDao.addThreeType(newId, threeType, createTime, "1");
        Integer twoThree = goodsDao.addTwoThree(twoId, newId, createTime, "1");
        if (integer > 0 && twoThree > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult deleteTypeThree(ShopThreeDTO shopThreeDTO) {
        Integer count = goodsDao.deleteThree(shopThreeDTO);
        if (count > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult updateTypeThree(ShopThreeDTO shopThreeDTO) {
        Integer count = goodsDao.updateThreeType(shopThreeDTO);
        if (count > 0) {
            return CommonResultUtil.Instance.success();
        }
        return CommonResultUtil.Instance.error();
    }

    @Override
    public JsonResult queryAllThree() {
        List<Map<String, Object>> mapList = goodsDao.queryAllThreeTyoe();
        return CommonResultUtil.Instance.success(mapList);
    }

}
